package com.itheima.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.itheima.config.OssProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import java.io.InputStream;

@Slf4j
@EnableConfigurationProperties(OssProperties.class)
@Component
public class AliossUtil {

    @Autowired
    private OssProperties ossProperties;
    public String uploadFile(String objectName, InputStream fis) {
        String fileUrl = "";
        OSS ossClient = null;
        try {
            String endpoint = ossProperties.getEndpoint();
            String bucketName = ossProperties.getBucketName();
            String accessKeyId = ossProperties.getAccessKeyId();
            String secretAccessKey = ossProperties.getSecretAccessKey();
            ossClient = new OSSClientBuilder().build("https://" + endpoint, accessKeyId, secretAccessKey);
            // 设置对象为公共读
//            ossClient.setObjectAcl(bucketName, objectName, CannedAccessControlList.PublicRead);
            ossClient.putObject(bucketName, objectName, fis);
            fileUrl = "https://" + bucketName + "." + endpoint + "/" + objectName;

        } catch (Exception oe) {
            log.error(oe.getMessage(),oe);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return fileUrl;
    }

}
